<template>
  <ul class="todo-main">
    <TodoItem v-for="(todo, index) in todos" :key="index" :todo="todo" />
  </ul>
</template>
<script>
import TodoItem from "./TodoItem/index";
export default {
  name: "TodoList",
  components: {
    TodoItem,
  },
  data() {
    return {
      todos: [
        { id: 1, name: "吃饭", isDone: true },
        { id: 2, name: "敲代码", isDone: false },
      ],
    };
  },
  beforeCreate() {
    console.log("listbeforeCreate");
  },
  created() {
    console.log("Listcreate");
  },
  beforeMount() {
    console.log("ListbeforeMount");
  },
  mounted() {
    console.log("listmounted");

    this.$globalBus.$on("add", this.addTodoName);
    this.$globalBus.$on("delOne", this.delOne);
    this.$globalBus.$on("updateOne", this.updateOne);
    this.$globalBus.$on("isCheckAll", this.isCheckAll);
    this.$globalBus.$on("delAll", this.delAll);
    //一上来就执行展示footer数据
    this.$globalBus.$emit("totalCount", this.todos);
    this.$globalBus.$emit("checkAllCount", this.todos);
  },
  beforeDestroy() {
    this.$globalBus.$off("add", this.addTodoName);
    this.$globalBus.$off("delOne", this.delOne);
    this.$globalBus.$off("updateOne", this.updateOne);
    this.$globalBus.$off("isCheckAll", this.isCheckAll);
    this.$$globalBus.$off("delAll", this.delAll);
  },
  watch: {
    todos: {
      handler() {
        console.log("listwatch");
        this.$globalBus.$emit("totalCount", this.todos);
        this.$globalBus.$emit("checkAllCount", this.todos);
      },
      deep: true,
      // 是在created
      immediate: true,
    },
  },
  methods: {
    // 添加
    addTodoName(name) {
      this.todos.push({
        id: Date.now(),
        name,
        isDone: false,
      });
    },
    // 删除一个
    delOne(id) {
      this.todos = this.todos.filter((item) => item.id !== id);
    },
    // 修改一个
    updateOne(id) {
      let todo = this.todos.find((item) => item.id === id);
      todo.isDone = !todo.isDone;
    },
    // 全选与全不选
    isCheckAll(val) {
      this.todos.forEach((item) => (item.isDone = val));
    },
    // 删除所有的完成
    delAll() {
      this.todos = this.todos.filter((item) => !item.isDone);
    },
  },
};
</script>

<style>
/*main*/
.todo-main {
  margin-left: 0px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: 0px;
}

.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}
</style>